package models

import (
	"context"
	"go-chain-data/global"
	"go.mongodb.org/mongo-driver/bson"
	"log"
)

type BlockTransactionInfo struct {
	Id                int64  `bson:"id"`
	ChainName         string `bson:"chainName"`
	ChainID           uint   `bson:"chainId"`
	LatestBlockHeight uint64 `bson:"latestBlockHeight"`
	BlockNumber       uint64 `bson:"blockNumber"`
	BlockHash         string `bson:"blockHash"`
	Status            uint64 `bson:"status"`
	TransactionHash   string `bson:"transactionHash"`
	GasUsed           uint64 `bson:"gasUsed"`
	GasPrice          string `bson:"gasPrice"`
	Timestamp         uint64 `bson:"timestamp"`
	TransactionFrom   string `bson:"from"`
	TransactionTo     string `bson:"to"`
	TransactionValue  string `bson:"value"`
	Logs              []Log  `bson:"logs"`
	Contract          string `bson:"contract"`
	IsTokenTransfer   uint8  `bson:"isTokenTransfer"`  // 0否 1是
	TransactionCount  int    `bson:"transactionCount"` //交易总数
	BlockRewards      string `bson:"blockRewards"`     //奖励
	Difficulty        string `bson:"difficulty"`       //块的困难程度
	Extra             string `bson:"extra"`
	ParentHash        string `bson:"parentHash"`
	Size              uint64 `bson:"size"`
	Cost              string `bson:"cost"`
	TransactionType   uint8  `bson:"transactionType"`
}

type Log struct {
	Address   string   `bson:"address"`
	Topics    []string `bson:"topics"`
	Data      string   `bson:"data"`
	TokenName string   `bson:"tokenName"`
	Decimals  uint8    `bson:"decimals"`
	SignName  string   `bson:"signName"`
}

func CreateOne(data BlockTransactionInfo) error {
	BlocksClient := global.DBEngine.Database(global.DbConfig.DbName).Collection("block_transaction_info_1")
	_, err := BlocksClient.InsertOne(context.Background(), data)
	return err
}

func DeleteByBlockNumber(blockNumber int64) error {
	filter := bson.D{
		{"blockNumber", bson.D{{"$gt", blockNumber}}},
		{"chainName", global.BlockChainConfig.Name},
		{"chainId", global.BlockChainConfig.Id},
	}

	blockClient := global.DBEngine.Database(global.DbConfig.DbName).Collection("block_transaction_info_1")
	// 执行删除操作
	_, err1 := blockClient.DeleteMany(context.Background(), filter)
	if err1 != nil {
		log.Println("删除block_transaction_info表失败:", err1)
		return err1
	}

	swapClient := global.DBEngine.Database(global.DbConfig.DbName).Collection("swap_transaction_info")
	_, err2 := swapClient.DeleteMany(context.Background(), filter)
	if err2 != nil {
		log.Println("删除swap_transaction_info表失败:", err2)
		return err1
	}

	return nil
}
